import {
  ApiOutlined,
  BarsOutlined,
  LinkOutlined,
  SearchOutlined,
  ThunderboltOutlined,
} from '@ant-design/icons';
import { ProTable } from '@ant-design/pro-components';
import { Card, Divider, Progress, Space, Tag } from 'antd';
import React from 'react';

type vsProps = {
  vs: any;
};

const VirtualServiceView: React.FC<vsProps> = (vs) => {
  console.log(vs.vs);

  const renderMatchConditions = (match: { uri: { prefix: any }; headers: any }) => {
    return (
      <ProTable
        search={false}
        toolBarRender={false}
        size="small"
        columns={[
          { title: '匹配类型', dataIndex: 'type' },
          { title: '条件', dataIndex: 'value' },
        ]}
        dataSource={[
          { type: 'URI', value: match?.uri?.prefix || '-' },
          { type: 'Headers', value: match?.headers ? JSON.stringify(match.headers) : '-' },
        ]}
        pagination={false}
      />
    );
  };

  // 处理目标服务分配
  const renderDestinations = (route: {
    match?: any;
    rewrite?: any;
    timeout?: any;
    retries?: any;
    route?: any[];
  }) => {

    const hasAnyWeight = route.route?.some(dest => dest.weight !== undefined);

    return (
      <div>
        {route.route?.map((dest, i) => (
          <div key={i}>
            <Progress
              percent={hasAnyWeight ? (dest.weight  ? dest.weight : 0) : 100}
              format={() => (
                <span>
                  <Tag>权重: {hasAnyWeight ? (dest.weight  ? dest.weight : 0) : 100}%</Tag>
                </span>
              )}
            />
            <div style={{ marginLeft: 16 }}>
              <Tag>目标：{dest.destination.host}</Tag>
              <Tag>子集: {dest.destination.subset || 'default'}</Tag>
              <Tag>端口: {dest.destination.port?.number || '80'}</Tag>
            </div>
            <Divider dashed />
          </div>
        ))}
      </div>
    );
  };

  const renderMatchTags = (match) => {
    return (
      <>
        <Space size={[4, 8]} wrap>
          {/* URI 匹配 */}
          {match.uri?.prefix && (
            <Tag icon={<LinkOutlined />} color="blue">
              URI前缀: {match.uri.prefix}
            </Tag>
          )}
          {match.uri?.exact && (
            <Tag icon={<LinkOutlined />} color="geekblue">
              URI精确: {match.uri.exact}
            </Tag>
          )}

          {/* Headers 匹配 */}
          {match.headers &&
            Object.entries(match.headers).map(([key, val]) => {
              const value = (val as any)?.exact || (val as any)?.regex;
              return (
                <Tag icon={<BarsOutlined />} color="purple" key={key}>
                  Header: "{key}: {value}"{(val as any)?.regex && ' (正则)'}
                </Tag>
              );
            })}

          {/* Method 匹配 */}
          {match.method && (
            <Tag icon={<ThunderboltOutlined />} color="orange">
              METHOD: {match.method}
            </Tag>
          )}

          {/* Query 参数 */}
          {match.queryParams &&
            Object.entries(match.queryParams).map(([key, val]) => (
              <Tag icon={<SearchOutlined />} color="cyan" key={key}>
                QUERY: {key}={(val as any)?.exact}
              </Tag>
            ))}

          {/* 特殊标记 */}
          {match.ignoreUriCase && (
            <Tag icon={<ApiOutlined />} color="gray">
              忽略大小写
            </Tag>
          )}
          {match.ignoreQueryParams && (
            <Tag icon={<ApiOutlined />} color="gray">
              忽略查询参数
            </Tag>
          )}
        </Space>
        <div style={{ paddingTop: 16 }}/>
      </>
    );
  };

  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 16 }}>
      {/* 遍历所有 HTTP 路由规则 */}
      {vs.vs.spec?.http?.map(
        (
          httpRoute: { match?: any; rewrite?: any; timeout?: any; retries?: any; route?: any[] },
          index: string,
        ) => (
          <Card
            key={index}
            title={`路由规则 #${index + 1}`}
            style={{ width: 1100 }}
            styles={{ header: { background: '#f0f8ff' } }}
          >
            {/* 匹配条件区块 */}
            <Divider
              orientation="left"
              orientationMargin={0}
              style={{
                borderLeft: '3px solid #5985f6', // 紫色
                paddingLeft: 6,
                height: 16,
                fontSize: 14,
              }}
            >
              匹配条件
            </Divider>
            {httpRoute.match?.map((match, index) => renderMatchTags(match))}

            {/* 目标服务区块 */}
            <Divider
              orientation="left"
              orientationMargin={0}
              style={{
                borderLeft: '3px solid #5985f6', // 紫色
                paddingLeft: 6,
                height: 16,
                fontSize: 14,
              }}
            >
              流量分配
            </Divider>
            {renderDestinations(httpRoute)}

            {/*/!* 其他配置（折叠显示） *!/*/}
            {/*<Collapse size="small">*/}
            {/*  <Collapse.Panel header="高级配置" key="1">*/}
            {/*    <pre style={{ fontSize: 12 }}>*/}
            {/*      {JSON.stringify(*/}
            {/*        {*/}
            {/*          rewrite: httpRoute.rewrite,*/}
            {/*          timeout: httpRoute.timeout,*/}
            {/*          retries: httpRoute.retries,*/}
            {/*        },*/}
            {/*        null,*/}
            {/*        2,*/}
            {/*      )}*/}
            {/*    </pre>*/}
            {/*  </Collapse.Panel>*/}
            {/*</Collapse>*/}
          </Card>
        ),
      )}
    </div>
  );
};
export default VirtualServiceView;
